<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/user.js'
import { useRouter } from 'vue-router'
import { showLoadingToast } from 'vant'

const router = useRouter()
const userStore = useUserStore()

const username = ref('')
const password = ref('')
const captcha = ref('')
const codeUrl = ref('/admin/common/captcha?rand=' + new Date().getTime())
const onSubmit = async (values) => {
  showLoadingToast({
    message: '正在登录中...',
    forbidClick: true
  })
  try {
    await userStore.login(values)
    await router.push('/')
  } catch (e) {
    refreshCode()
  }
}

const refreshCode = () => {
  codeUrl.value = '/admin/common/captcha?rand=' + new Date().getTime()
}
</script>

<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        autocomplete="username"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        autocomplete="password"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        center
        v-model="captcha"
        type="text"
        name="captcha"
        label="验证码"
        placeholder="验证码"
        :rules="[{ required: true, message: '请填写验证码' }]"
      >
        <template #button>
          <img style="height: 40px" :src="codeUrl" @click="refreshCode" alt="" />
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit"> 提交</van-button>
    </div>
  </van-form>
</template>

<style scoped></style>
